package com.infindo.twitter;

import java.net.URL;
import java.util.Vector;

import com.infindo.twitter.UsersHandler.UsersHandlerType;

import android.util.Xml;
import android.util.Xml.Encoding;

public class UserRequest {

		private final static String TWITTER_URL = "http://www.twitter.com";
		private final static String TWITTER_USER_ID_URL = "/users/show.xml?user_id=";
		private final static String TWITTER_USER_SCREEN_NAME_URL = "/users/show.xml?screen_name=";
		private final static String TWITTER_USER_FRIENDS = "/statuses/friends.xml";
	
       private Vector<UserListener> listeners = new Vector<UserListener>();

       public void addListener(UserListener listener) {
               this.listeners.add(listener);
       }
      
       public void start(final Object Id, final UsersHandlerType usersHandlerType) {
               new Thread(new Runnable() {

                       public void run() {
                              
	                   		try {
	
	                			URL url = null;
	                			if (usersHandlerType == UsersHandlerType.ID) {
	                				url = new URL(TWITTER_URL + TWITTER_USER_ID_URL + String.valueOf(Id));	
	                			} else if (usersHandlerType == UsersHandlerType.SCREENNAME) {
	                				url = new URL(TWITTER_URL + TWITTER_USER_SCREEN_NAME_URL + String.valueOf(Id));
	                			}
	                			
	                			url.openConnection();
	
	                			UsersHandler usersHandler = new UsersHandler(usersHandlerType);
	                			                			
	                			Xml.parse(url.openStream(), Encoding.UTF_8, usersHandler);
	
	                			raiseCompletedEvent(usersHandler.GetUser(Integer.parseInt(String.valueOf(Id))));
	
	                		} catch (Exception e) {
	                			// Toast.makeText(this, "Error setting up user", Toast.LENGTH_SHORT).show();
	                			raiseErrorEvent(e);
	                		}
                       }
                      
               }).start();
       }
      
       private void raiseCompletedEvent(User user) {
               for(UserListener listener : this.listeners) {
                       listener.onCompleted(user);
               }
       }
      
       private void raiseErrorEvent(Throwable ex) {
               for(UserListener listener : this.listeners) {
                       listener.onError(ex);
               }
       }
      
}
